import React, {useCallback, useEffect, useRef, useState} from "react"
import {
    addMarketReturnOrderItem,
    AddMarketReturnOrderItemRequest, deleteMarketReturnOrderItem,
    getMarketReturnOrderDetail,
    MarketReturnOrderDetail,
    MarketReturnOrderItem, submitMarketReturnOrder, updateMarketReturnOrderItemAmount, validateMarketReturnOrder
} from "../../apis/MarketReturnOrderApi";
import {Button, Col, Descriptions, InputNumber, Row, Space, theme} from "antd";
import {OffsetDateTime} from "@js-joda/core";
import {convertAntdTableToExcel, ExportedColumnProps} from "../../utils/AntdTableUtils";
import {
    getAllGoodsWithMarketInStore,
    getAllGoodsWithMarketInStoreInMakret,
    GoodsWithMarketInStore
} from "../../apis/GoodsApi";
import AuthorizationResource from "../../components/AuthorizationResource";
import {DeleteOutlined} from "@ant-design/icons";
import DataPageLayout from "../../components/DataPageLayout";
import ArrayUtils from "@zxy-cn/array-utils";
import SingleInputPopover from "../../components/SingleInputPopover";
import dashboardPageStore from "../../store/DashboardPageStore";
import {observerDashboardPageWrapper} from "../../components/dashboardPages/ObserverDashboardPageWrapper";
import employeeAuthorizationStore from "../../store/EmployeeAuthorizationStore";
import LoadableButton from "../../components/LoadableButton";
import EditOrderItemRow from "../../components/EditOrderItemRow";
import {saveWorkbookTo} from "../../utils/FileSaver";
import GoodsTable from "../../components/GoodsTable";
import {DATE_WITH_TIME_FORMATER} from "../../utils/Date";


export interface pageProps {
    id: number
}

const myPath = "markets/returnOrders/{id}"

const MarketReturnOrderDetailPage: React.FC<pageProps> = ({id}) => {
    const [loading, setLoading] = useState(false)
    const [data, setData] = useState<MarketReturnOrderDetail>()
    const query = useCallback(() => {
        setLoading(true)
        getMarketReturnOrderDetail(id).then(response => {
            dashboardPageStore.setTitle(myPath.replace("{id}", id.toString()), response.data.market.name + "退货单")
            setData(response.data)
        }).finally(() => {
            setLoading(false)
        })
    }, [id])

    useEffect(() => {
        query()
    }, [query]);

    let token = theme.useToken();

    let columnsRef = useRef<ExportedColumnProps<MarketReturnOrderItem>[]>();

    return (
        <>
            {!loading ? <Descriptions title={"订单明细"}>
                <Descriptions.Item label={"卖场"}>{data?.market?.name}</Descriptions.Item>
                <Descriptions.Item label={"下单人"}>{data?.createdBy?.name}</Descriptions.Item>
                {!!data?.submittedDateTime && <Descriptions.Item
                    label={"下单时间"}>{data?.submittedDateTime.format(DATE_WITH_TIME_FORMATER)}</Descriptions.Item>}
                {!!data?.validatedDateTime ? <Descriptions.Item
                    label={"验收"}>{data.validatedDateTime.format(DATE_WITH_TIME_FORMATER)}</Descriptions.Item> : undefined}

            </Descriptions> : null}
            <Row gutter={8} style={{margin: "12px 0"}}>
                <Col>
                    <LoadableButton onClick={async (event) => {
                        let workbook = await convertAntdTableToExcel(columnsRef.current!!, data?.items ?? []);
                        await saveWorkbookTo(workbook, `${data?.market?.name}订单-${data?.submittedDateTime ?? data!.createdDateTime.format(DATE_WITH_TIME_FORMATER)}`)
                    }}>
                        导出
                    </LoadableButton>
                </Col>
                {employeeAuthorizationStore.hasAuthority("卖场_退货单_验收")
                && !data?.validatedDateTime
                && !!data?.submittedDateTime ?
                    <Col>
                        <LoadableButton onClick={async () => {
                            await validateMarketReturnOrder(id)
                            setData({...data!, validatedDateTime: OffsetDateTime.now()})
                        }}>验收</LoadableButton>
                    </Col> : undefined}
                {employeeAuthorizationStore.hasAuthority("卖场_退货单_下单") && !data?.submittedDateTime &&
                    <Col>
                        {!!data && <LoadableButton onClick={async (event) => {
                            await submitMarketReturnOrder(data?.id)
                            setData({...data!, submittedDateTime: OffsetDateTime.now()})
                        }}>
                            提交订单
                        </LoadableButton>}

                    </Col>}
                {<Col>
                    <LoadableButton onClick={async (_) => {
                    // await submitMarketReturnOrder(id)
                    // setData({...data!, submitDateTime: OffsetDateTime.now()})
                }}>
                    打印
                </LoadableButton></Col>}
            </Row>

            {((employeeAuthorizationStore.hasAuthority("卖场_退货单_下单") && !data?.submittedDateTime) || (employeeAuthorizationStore.hasAuthority("卖场_退货单_修改") && !data?.validatedDateTime)) &&
                !!data &&
                <EditOrderItemRow<GoodsWithMarketInStore>
                    request={{editMarketReturnOrderId: id}}
                    fetchGoods={() =>
                        getAllGoodsWithMarketInStoreInMakret(data.market.id).then(res => {
                            return res.data
                        })}
                    optionRender={it =>  <div style={{display: 'flex', flexDirection: "column"}}>
                        <div style={{display: "flex", justifyContent: 'space-between'}}>
                            <span>{it.barcode}</span><span>{it.name}</span>
                        </div>
                        <Space size={24}><span>卖场存货:{it.amountInMarket??"无"}</span><span>库存:{it.amount}</span></Space>
                    </div>}
                    onFinish={async (values) => {
                        return addMarketReturnOrderItem(id, values).then(() => {
                            query()
                        })
                    }} existedGoodsKeys={data?.items?.map(it => ({goodsId:it.id})) ?? []}/>}
            <DataPageLayout leftActions={<>
            </>}>

                <GoodsTable<MarketReturnOrderItem> loading={loading}
                                             size={"small"}
                                             customColumns={columns => {
                                                 ArrayUtils.insertAfter(columns, value => value.dataIndex === "name", {
                                                     dataIndex: "amountInOrder",
                                                     title: "数量",
                                                     render: (value, record) => {
                                                         return <div
                                                             style={{color: record.amountInOrder > record.amount && !data?.validatedDateTime ? token.token.colorError : undefined}}>{value}</div>
                                                     }
                                                 },)
                                                 columns.push({
                                                     ignoreInExcel: true,
                                                     title: "操作",
                                                     render: (_, item, index) => {
                                                         return <>
                                                             {employeeAuthorizationStore.hasAuthority("卖场_退货单_下单") && !data?.validatedDateTime &&
                                                                 <SingleInputPopover required title={"修改单品数量"}
                                                                                     rules={[{type: "number", min: 0}]}
                                                                                     onConfirm={async value => {
                                                                                         let amount = parseInt(value);
                                                                                         await updateMarketReturnOrderItemAmount(id, item.id, {amount})
                                                                                         let items = Array.from(data?.items ?? []);
                                                                                         items[index].amountInOrder = amount
                                                                                         setData({
                                                                                             ...data!,
                                                                                             items
                                                                                         })
                                                                                     }} fieldName={"货品数量"}
                                                                                     customInput={(props, ref) => {
                                                                                         return <InputNumber
                                                                                             placeholder={props.placeholder}
                                                                                             style={{width: "100%"}}
                                                                                             autoFocus={props.autoFocus}
                                                                                             min={0}
                                                                                             defaultValue={1}/>
                                                                                     }}>
                                                                     <Button type={"link"}>修改数量</Button>
                                                                 </SingleInputPopover>}

                                                             <AuthorizationResource
                                                                 authorities={["卖场_退货单_修改"]}>
                                                                 <Button type={"link"}
                                                                         danger
                                                                         onClick={() => {
                                                                             deleteMarketReturnOrderItem(id, item.id).then(() => {
                                                                                 let items = Array.from(data!.items);
                                                                                 ArrayUtils.remove(items, item)
                                                                                 setData({
                                                                                     ...data!,
                                                                                     items
                                                                                 })
                                                                             })
                                                                         }}>
                                                                     <DeleteOutlined/>
                                                                     删除
                                                                 </Button>
                                                             </AuthorizationResource>
                                                         </>
                                                     }

                                                 },);
                                                 columnsRef.current = columns;
                                                 return columns;
                                             }}
                                             rowKey={"id"} data={data?.items ?? []}>
                </GoodsTable>
            </DataPageLayout>

        </>
    )
}

export default observerDashboardPageWrapper(MarketReturnOrderDetailPage, myPath, "卖场退货单详情")

